package com.example.musicaiap.data.database.dao

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import com.example.musicaiap.data.database.PlaylistSongCrossRef
import com.example.musicaiap.data.database.SongEntity
import kotlinx.coroutines.flow.Flow

/**
 * 播放列表与歌曲关系的数据访问对象
 * 管理播放列表中包含的歌曲
 */
@Dao
interface PlaylistSongDao {
    
    /**
     * 将歌曲添加到播放列表
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun addSongToPlaylist(playlistSongCrossRef: PlaylistSongCrossRef)
    
    /**
     * 批量将歌曲添加到播放列表
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun addSongsToPlaylist(playlistSongCrossRefs: List<PlaylistSongCrossRef>)
    
    /**
     * 从播放列表中移除歌曲
     */
    @Query("DELETE FROM playlist_song_cross_refs WHERE playlistId = :playlistId AND songId = :songId")
    suspend fun removeSongFromPlaylist(playlistId: String, songId: String)
    
    /**
     * 获取播放列表中的所有歌曲ID
     */
    @Query("SELECT songId FROM playlist_song_cross_refs WHERE playlistId = :playlistId ORDER BY position ASC")
    suspend fun getSongIdsInPlaylist(playlistId: String): List<String>
    
    /**
     * 清空播放列表中的所有歌曲
     */
    @Query("DELETE FROM playlist_song_cross_refs WHERE playlistId = :playlistId")
    suspend fun clearPlaylist(playlistId: String)
    
    /**
     * 删除播放列表及其所有关联
     */
    @Transaction
    suspend fun deletePlaylistWithSongs(playlistId: String) {
        clearPlaylist(playlistId)
    }
    
    /**
     * 获取包含特定歌曲的所有播放列表ID
     */
    @Query("SELECT playlistId FROM playlist_song_cross_refs WHERE songId = :songId")
    suspend fun getPlaylistsContainingSong(songId: String): List<String>
    
    /**
     * 统计播放列表中的歌曲数量
     */
    @Query("SELECT COUNT(*) FROM playlist_song_cross_refs WHERE playlistId = :playlistId")
    suspend fun countSongsInPlaylist(playlistId: String): Int
    
    /**
     * 获取非挂起版本，用于媒体服务
     */
    @Query("SELECT songId FROM playlist_song_cross_refs WHERE playlistId = :playlistId ORDER BY position ASC")
    fun getSongIdsInPlaylistSync(playlistId: String): List<String>
    
    /**
     * 检查歌曲是否在指定播放列表中
     */
    @Query("SELECT COUNT(*) > 0 FROM playlist_song_cross_refs WHERE playlistId = :playlistId AND songId = :songId")
    suspend fun isSongInPlaylist(playlistId: String, songId: String): Boolean
    
    /**
     * 获取播放列表中的最大位置
     */
    @Query("SELECT MAX(position) FROM playlist_song_cross_refs WHERE playlistId = :playlistId")
    suspend fun getMaxPositionInPlaylist(playlistId: String): Int
    
    /**
     * 获取播放列表中的所有歌曲（Flow版本）
     */
    @Query("SELECT s.* FROM songs s INNER JOIN playlist_song_cross_refs ps ON s.id = ps.songId WHERE ps.playlistId = :playlistId ORDER BY ps.position ASC")
    fun getSongsInPlaylistFlow(playlistId: String): Flow<List<SongEntity>>
} 